﻿using System;
using System.Web;

namespace CoolCode.Web
{
    public class RequestUtility
    {
        /// <summary>
        /// 判断当前页面是否接收到了Post请求
        /// </summary>
        /// <returns>是否接收到了Post请求</returns>
        public static bool IsPost()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("POST");
        }

        /// <summary>
        /// 判断当前页面是否接收到了Get请求
        /// </summary>
        /// <returns>是否接收到了Get请求</returns>
        public static bool IsGet()
        {
            return HttpContext.Current.Request.HttpMethod.Equals("GET");
        }

        /// <summary>
        /// 返回指定的服务器变量信息
        /// </summary>
        /// <param name="strName">服务器变量名</param>
        /// <returns>服务器变量信息</returns>
        public static string GetServerString(string strName)
        {
            //
            if (HttpContext.Current.Request.ServerVariables[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.ServerVariables[strName].ToString();
        }

        /// <summary>
        /// 返回上一个页面的地址
        /// </summary>
        /// <returns>上一个页面的地址</returns>
        public static string GetUrlReferrer()
        {
            string retVal = null;

            try
            {
                retVal = HttpContext.Current.Request.UrlReferrer.ToString();
            }
            catch { }

            if (retVal == null)
                return "";

            return retVal;

        }

        /// <summary>
        /// 得到当前完整主机头
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHost()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            if (!request.Url.IsDefaultPort)
            {
                return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
            }
            return request.Url.Host;
        }

        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }


        /// <summary>
        /// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
        /// </summary>
        /// <returns>原始 URL</returns>
        public static string GetRawUrl()
        {
            return HttpContext.Current.Request.RawUrl;
        }

        /// <summary>
        /// 判断当前访问是否来自浏览器软件
        /// </summary>
        /// <returns>当前访问是否来自浏览器软件</returns>
        public static bool IsBrowserGet()
        {
            string[] BrowserName = { "ie", "opera", "netscape", "mozilla", "konqueror", "firefox" };
            string curBrowser = HttpContext.Current.Request.Browser.Type.ToLower();
            for (int i = 0; i < BrowserName.Length; i++)
            {
                if (curBrowser.IndexOf(BrowserName[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public static bool IsSearchEnginesGet()
        {
            if (HttpContext.Current.Request.UrlReferrer == null)
            {
                return false;
            }
            string[] SearchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou" };
            string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            for (int i = 0; i < SearchEngine.Length; i++)
            {
                if (tmpReferrer.IndexOf(SearchEngine[i]) >= 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 获得当前完整Url地址
        /// </summary>
        /// <returns>当前完整Url地址</returns>
        /// <remarks>Updated in May 19, 2009 </remarks>
        /// <example> Remark: If current URL is
        ///    http://localhost/search.aspx?url=http://www.sample.com&tag=%BC%BC%CA%F5
        ///   using HttpContext.Current.Request.Url.ToString() will show a wrong result:
        ///   http://localhost/search.aspxurl=http://www.sample.com&tag=&frac14;&frac14;&Ecirc;&otilde;            
        /// </example>
        public static string GetUrl()
        {
            return HttpContext.Current.Request.Url.PathAndQuery;
            /*Old method as follow*/
            // return HttpContext.Current.Request.Url.ToString();
        }

        /// <summary>
        ///  
        /// </summary>
        /// <returns> </returns>
        public static string GetMainUrl()
        {
            string curUrl = GetUrl();
            string pageName = GetPageName();
            return curUrl.Replace("/" + pageName, "");
        }

        /// <summary>
        /// Add in Mar 16, 2009
        /// </summary>
        /// <param name="relativeUrl"></param>
        /// <returns></returns>
        public static string GetAbsoluteUrl(string relativeUrl)
        {
            string cur = GetUrl();
            cur = GetParent(cur);
            while (relativeUrl.StartsWith("../"))
            {
                relativeUrl = relativeUrl.Substring(3);
                cur = GetParent(cur);
            }
            if (!relativeUrl.StartsWith("/"))
                relativeUrl = "/" + relativeUrl;
            return cur + relativeUrl;
        }

        /// <summary>
        /// Add in Mar 16, 2009
        /// </summary>
        /// <param name="cur"></param>
        /// <returns></returns>
        private static string GetParent(string cur)
        {
            int ind = cur.LastIndexOf("/");
            if (ind > 5)
                cur = cur.Remove(ind);
            if (cur.EndsWith("/"))
                cur = cur.Remove(cur.Length - 1);
            return cur;
        }


        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的值</returns>
        public static string GetQueryString(string strName)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)
            {
                return "";
            }
            return Utility.UrlDecode(HttpContext.Current.Request.QueryString[strName]);
        }

        /// <summary>
        ///  Get Query String (Add in Mar 18, 2009)
        /// </summary>
        /// <param name="strName">Url parameter</param>
        /// <param name="defaultValue">Default Value</param>
        /// <returns></returns>
        public static string GetQueryString(string strName, string defaultValue)
        {
            if (HttpContext.Current.Request.QueryString[strName] == null)
            {
                return defaultValue;
            }
            return Utility.UrlDecode(HttpContext.Current.Request.QueryString[strName]);
        }

        /// <summary>
        ///  Get Query Date (Add in Mar 18, 2009)
        /// </summary>
        /// <param name="strName">Url parameter</param>
        /// <param name="defaultValue">Default Value</param>
        /// <returns></returns>
        public static DateTime GetQueryString(string strName, DateTime defaultValue)
        {
            if (string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[strName] ))
            {
                return defaultValue;
            }
            return DateTime.Parse(Utility.UrlDecode(HttpContext.Current.Request.QueryString[strName]));
        }

        /// <summary>
        ///  Get Query Boolean Value (Add in Mar 18, 2009)
        /// </summary>
        /// <param name="strName">Url parameter</param>
        /// <param name="defaultValue">Default Value</param>
        /// <returns></returns>
        public static bool GetQueryString(string strName, bool defaultValue)
        {
            string query = HttpContext.Current.Request.QueryString[strName];
            if (string.IsNullOrEmpty(query))
            {
                return defaultValue;
            }
            query = query.Trim();
            if (query.ToUpper() == "N" || query == "0") return false;
            else if (query.ToUpper() == "Y" || query == "1") return true;
            return bool.Parse(query);
        }

        /// <summary>
        ///  Get Query Integer Value (Add in Apr 20, 2009)
        /// </summary>
        /// <param name="strName">Url parameter</param>
        /// <param name="defaultValue">Default Value</param>
        /// <returns></returns>
        public static int GetQueryString(string strName, int defaultValue)
        {
            if (string.IsNullOrEmpty( HttpContext.Current.Request.QueryString[strName] ))
            {
                return defaultValue;
            }
            return int.Parse(Utility.UrlDecode(HttpContext.Current.Request.QueryString[strName]));
        }

        /// <summary>
        /// 获得当前页面的名称
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return urlArr[urlArr.Length - 1];
        }

        /// <summary>
        /// 返回表单和Url参数的总个数
        /// </summary>
        /// <returns></returns>
        public static int GetParamCount()
        {
            return HttpContext.Current.Request.Form.Count + HttpContext.Current.Request.QueryString.Count;
        }


        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>表单参数的值</returns>
        public static string GetFormString(string strName)
        {
            if (HttpContext.Current.Request.Form[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.Form[strName];
        }

        /// <summary>
        /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值
        /// </summary>
        /// <param name="strName">参数</param>
        /// <returns>Url或表单参数的值</returns>
        public static string GetString(string strName)
        {
            if ("".Equals(GetQueryString(strName)))
            {
                return GetFormString(strName);
            }
            else
            {
                return GetQueryString(strName);
            }
        }


        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (string.IsNullOrEmpty(result))// || !Utils.IsIP(result))
            {
                return "127.0.0.1";
            }

            return result;

        }

        /// <summary>
        /// 保存用户上传的文件
        /// </summary>
        /// <param name="path">保存路径</param>
        public static void SaveRequestFile(string path)
        {
            if (HttpContext.Current.Request.Files.Count > 0)
            {
                HttpContext.Current.Request.Files[0].SaveAs(path);
            }
        }

        private static string _root = null;
        public static string Root
        {
            get
            {
                if (_root == null)
                {
                    _root = HttpContext.Current.Request.ApplicationPath;
                    _root = (_root.EndsWith("/") ? _root.Remove(_root.Length - 1) : _root);
                }
                return _root;
            }
        }


        /// <summary>
        ///  Join Query String (Add in May 04, 2009)
        /// </summary>
        /// <param name="strName">Url parameter</param> 
        /// <remarks>Get value from querystring and rebuilt it for other page</remarks>
        /// <returns></returns>
        public static string JoinQueryString(string strName)
        {
            return JoinQueryString(strName, string.Empty);
        }

        /// <summary>
        ///  Join Query String (Add in May 04, 2009)
        /// </summary>
        /// <param name="strName">Url parameter</param>
        /// <param name="defaultValue">Default Value</param>
        /// <remarks>Get value from querystring and rebuilt it for other page</remarks>
        /// <returns></returns>
        public static string JoinQueryString(string strName, string defaultValue)
        {
            string strValue = GetQueryString(strName, defaultValue);
            return strName + "=" + strValue;
        }

        /// <summary>
        ///  Join Query String (Add in May 04, 2009)
        /// </summary>
        /// <param name="strNames">Url parameter array</param> 
        /// <remarks>Get value from querystring and rebuilt it for other page</remarks>
        /// <returns></returns>
        public static string JoinQueryString(params  string[] strNames)
        {
            string strValue = string.Empty;
            foreach (string strName in strNames)
                strValue += JoinQueryString(strName) + "&";
            return strValue;
        }

    }
}
